<template>
  <div>
    <el-upload class="upload-demo" ref="upload" :on-exceed='handleExceed' :accept='acceptType' :on-change='beforeUpload' :http-request='uploadFile' action="" :on-error='handleError' :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" list-type="picture-card" :auto-upload="false" :before-remove="beforeRemove" :limit='uploadLimit' :on-success='handleSuccess' :disabled="disabledFlag">
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import {
  createAppUrlByWrite,
  deleteAppFile,
  createAppUrlByRead
} from "@/api/common/aliyunoss";

export default {
  name: "uploadList",
  props: {
    propFileList: {
      type: Array,
      default() {
        return [];
      }
    },
    disabledFlag: {
      type: Boolean,
      default: false
    },
    uploadLimit: {
      type: Number,
      default: 1
    },
    afterUploadFiles: {
      type: Function
    }
  },
  data() {
    return {
      fileList: this.propFileList,
      removeFileList: [],
      uploadFinishFileList: this.propFileList,
      dialogVisible: false,
      acceptTypes: ["image/png", "image/jpeg"],
      acceptType: ".jpg,.png,.jpeg,",
      dialogImageUrl: ""
    };
  },
  mounted() {},
  watch: {
    // uploadFinishFileList(val) {
    //   this.$emit("on-result-change", val);
    // }
  },
  methods: {
    submitUpload() {
      //删除已经上传过的文件
      for (let elem of this.removeFileList) {
        if (elem) {
          const condition = {
            fileName: elem.uploadFileName
          };
          console.log("删除已经上传过的文件");
          deleteAppFile(condition).catch();
        }
      }
      this.$refs.upload.submit();
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove(file, fileList) {
      let target = null;
      let ind = null;
      for (let [index, elem] of this.uploadFinishFileList.entries()) {
        if (elem.uid == file.uid) {
          target = elem;
          ind = index;
          break;
        }
      }
      if (target) {
        this.removeFileList.push({
          uid: target.uid,
          uploadFileName: target.uploadFileName
        });
        this.uploadFinishFileList.splice(ind, 1);
      }
    },
    handleSuccess(response, file, fileList) {
    },
    handleError(err, file, fileList) {
      this.$message.error("服务器出现点问题，请重试。");
    },
    uploadFile(options) {
      let that = this;
      let extFile = "";
      switch (options.file.type) {
        case "image/jpeg": {
          extFile = "jpg";
          break;
        }
        case "image/png": {
          extFile = "png";
          break;
        }
      }

      const condition = {
        contentType: options.file.type,
        extFile: extFile
      };
      // options.onSuccess()
      createAppUrlByWrite(condition).then(response => {
        const uploadPath = response.data.data.url;
        const uploadFileName = response.data.data.fileName;
        var config = {
          onUploadProgress: options.onProgress,
          headers: {
            "Access-Control-Allow-Origin": "*",
            "Content-Type": options.file.type,
            "Content-Encoding": "utf-8",
            "Cache-control": "no-cache"
          }
        };
        axios
          .put(uploadPath, options.file, config)
          .then(function(res) {
            that.uploadFinishFileList.push({
              uid: options.file.uid,
              uploadFileName: uploadFileName
            });
            options.onSuccess();
          })
          .catch(function(err) {
            options.onError();
          });
      });
    }, // 预览图片
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ` + this.uploadLimit + ` 个文件!`);
    },
    beforeUpload(file, fileList) {
      let isPngJpg = this.acceptTypes.includes(file.raw.type);
      if (!isPngJpg) {
        this.$message.warning("只能上传 PNG / JPG 格式的图片");
        fileList.pop();
        return false;
      }
      let isLt1M = file.raw.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        this.$message.warning("单张图片不得大于 1 MB 的限制");
        fileList.pop();
        return false;
      }
      return true;
    }
  }
};
</script>

